//
//  YWSelectMaterialTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/2.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWSelectMaterialTableViewController.h"
#import "YWMaterialInfoTableViewCell.h"
#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "PinYin4Objc.h"
#import "pinyin.h"
#import "YWCommonTool.h"
#import "MJRefresh.h"

#import "YWMaterialManager.h"
#import "YWMaterialStock.h"
#import "YWMaterial.h"
#import "YWCommonTool.h"
#import "YWBuilding.h"
#import "YWEmptyTableViewCell.h"

@interface YWSelectMaterialTableViewController ()<UISearchBarDelegate,UISearchControllerDelegate>{
    NSInteger page;
    NSString * searchCondition;//搜索条件
}
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *selectedArray;;

//搜索的控制器
@property (nonatomic, strong) UISearchController *searchController;

@end

@implementation YWSelectMaterialTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加物料";
    page = 1;
    
    [self refreshTop];
    
    [self initTableView];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonClickEvent:)];
    
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0f;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    //刷新
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    [self.tableView registerClass:[YWMaterialInfoTableViewCell class] forCellReuseIdentifier:YWMaterialInfoTableViewCellIdentifier];
    [self.tableView registerClass:[YWEmptyTableViewCell class] forCellReuseIdentifier:YWEmptyTableViewCellIdentifier];
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.delegate = self;
    //_searchController.searchResultsUpdater = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    _searchController.searchBar.delegate = self;
    [_searchController.searchBar sizeToFit];
    
    UIColor *color =  [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0];
    _searchController.searchBar.layer.borderWidth = 1;
    _searchController.searchBar.layer.borderColor = [color CGColor];
    _searchController.searchBar.barTintColor = color;
    [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@"取消"];
    self.tableView.tableHeaderView = _searchController.searchBar;
//    [self.tableView setEditing:YES];
}

- (void)refreshTop
{
    page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType
{
    if (refreshType == YWTableViewFreshTypeUp) {
        page++;
    }
    YWWeakSelf(weakSelf);
     [[YWMaterialManager shareManager] requestSearchMaterialListWithBuildingId:self.building.buildingId SearchCondition:searchCondition page:page WithComplete:^(NSArray *searchResult,NSInteger statusCode) {
         dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
             if (statusCode ==200) {
                 if (searchResult.count) {
                     [self.dataSource addObjectsFromArray:searchResult];
                     //去除数据源中跟已选中的相同的项
                     for (int i=0; i< self.dataSource.count; i++) {
                         YWMaterialStock *beforeStock = self.dataSource[i];
                         for (int j=0; j< self.selectedArray.count; j++) {
                             YWMaterialStock *nowStock = self.selectedArray[j];
                             if (beforeStock.stockId == nowStock.stockId) {
                                 [self.dataSource removeObject:beforeStock];
                                 i--;
                             }
                         }
                     }
                     [self.dataSource addObjectsFromArray:self.selectedArray];
                     self.dataSource = (NSMutableArray *)[[self.dataSource reverseObjectEnumerator] allObjects];
                     [self.tableView reloadData];
                 }
             }else{
                 [YWCommonTool showTextHUDWithContent:@"获取物料清单失败!"];
             }
        });
    }];
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
//        _dataSource = [[YWMaterialManager shareManager] materialStockWithPage:page];
    
    }
    return _dataSource;
}

- (NSMutableArray *)selectedArray{
    if (!_selectedArray) {
        _selectedArray = [NSMutableArray array];
    }
    return _selectedArray;
}

- (void)setOwnMaterialArray:(NSMutableArray *)ownMaterialArray{
    _ownMaterialArray = ownMaterialArray;
    [self.selectedArray addObjectsFromArray:ownMaterialArray];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count>0?self.dataSource.count : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataSource.count>0) {
        YWMaterialInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMaterialInfoTableViewCellIdentifier];
        [self configureCell:cell atIndexPath:indexPath];
        return cell;
    }else{
        YWEmptyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWEmptyTableViewCellIdentifier];
        return cell;
    }
}

- (void)configureCell:(YWMaterialInfoTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    YWMaterialStock * materialStock = self.dataSource[indexPath.row];
    if (self.selectedArray) {
       cell.selectedArray = self.selectedArray;
    }
    cell.materialStock = materialStock;

}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [tableView fd_heightForCellWithIdentifier:YWMaterialInfoTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialInfoTableViewCell *cell) {
//            [self configureCell:cell atIndexPath:indexPath];
//        }];
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.dataSource.count>0) {
        YWMaterialStock *materialStock = self.dataSource[indexPath.row];
        
        NSString *quantity = [NSString stringWithFormat:@"可用数量%ld",(long)materialStock.quantity];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:materialStock.materialInfo.materialName?:@"" message:quantity preferredStyle:UIAlertControllerStyleAlert];
        [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            textField.placeholder = @"填写申请的数量";
            textField.keyboardType = UIKeyboardTypeNumberPad;
        }];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            UITextField *textField = alert.textFields.count ? alert.textFields[0] : nil;
            NSInteger selectQuantity = [textField.text integerValue];
            if (selectQuantity>materialStock.quantity || selectQuantity == 0) {
                NSString *message = selectQuantity == 0 ? @"数量不能为0" : @"数量不能大于库存数量";
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]];
                [(_searchController.active ? _searchController : self) presentViewController:alert animated:YES completion:nil];
            }else{
                __block BOOL isContain = NO;
                [self.selectedArray enumerateObjectsUsingBlock:^(YWMaterialStock * _Nonnull stock, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (materialStock.stockId == stock.stockId) {
                        stock.selectQuantity = selectQuantity;
                        isContain = YES;
                        *stop = YES;
                    }
                }];
                if (!isContain) {
                    materialStock.selectQuantity = selectQuantity;
                    [self.selectedArray addObject:materialStock];
                }
                [self selectMaterialAfter];
                [_searchController setActive:NO];
                [self.tableView reloadData];
            }
        }]];
        [(_searchController.active ? _searchController : self) presentViewController:alert animated:YES completion:nil];
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSString *searchString = searchBar.text;
    searchCondition = searchString;
    page = 1;
    [[YWMaterialManager shareManager] requestSearchMaterialListWithBuildingId:self.building.buildingId SearchCondition:searchCondition page:page WithComplete:^(NSArray *searchResult,NSInteger statusCode) {
        if (statusCode == 200) {
            _dataSource = nil;
            
            if (searchResult.count) {
                [self.dataSource addObjectsFromArray:searchResult];
                //如果搜索结果包含已选择的，去掉搜索结果的相同项然后加上已选择的相同项
                if (self.selectedArray) {
                    [self.dataSource enumerateObjectsUsingBlock:^(YWMaterialStock *  _Nonnull beforeStock, NSUInteger idx, BOOL * _Nonnull stop) {
                        [self.selectedArray enumerateObjectsUsingBlock:^(YWMaterialStock * _Nonnull nowStock, NSUInteger idxNow, BOOL * _Nonnull stop) {
                            if (beforeStock.stockId == nowStock.stockId) {
                                [self.dataSource replaceObjectAtIndex:idx withObject:nowStock];
                                *stop = YES;
                            }
                        }];
                    }];
                }
            }else{
                [YWCommonTool showTextHUDWithContent:@"未找到相关信息!"];
            }
            [self.tableView reloadData];
        }else{
            [YWCommonTool showTextHUDWithContent:@"获取物料清单失败!"];
        }
    }];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self selectMaterialAfter];
}

- (void)selectMaterialAfter{
    page = 1;
    [[YWMaterialManager shareManager] requestSearchMaterialListWithBuildingId:self.building.buildingId SearchCondition:@"" page:page WithComplete:^(NSArray *searchResult,NSInteger statusCode) {
        if (statusCode ==200) {
            if (searchResult.count) {
                self.dataSource = nil;
                [self.dataSource addObjectsFromArray:searchResult];
                //去除数据源中跟已选中的相同的项
                for (int i=0; i< self.dataSource.count; i++) {
                    YWMaterialStock *beforeStock = self.dataSource[i];
                    for (int j=0; j< self.selectedArray.count; j++) {
                        YWMaterialStock *nowStock = self.selectedArray[j];
                        if (beforeStock.stockId == nowStock.stockId) {
                            [self.dataSource removeObject:beforeStock];
                            i--;
                        }
                    }
                }
                [self.dataSource addObjectsFromArray:self.selectedArray];
                self.dataSource = (NSMutableArray *)[[self.dataSource reverseObjectEnumerator] allObjects];
                [self.tableView reloadData];
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            }
        }else{
            [YWCommonTool showTextHUDWithContent:@"获取物料清单失败!"];
        }
    }];
}

- (void)rightBarButtonClickEvent:(id)sender{
    if ([self.delegate respondsToSelector:@selector(popSelectMaterials:)]) {
        //去除之前已选择的物料
        for (int i=0; i< self.ownMaterialArray.count; i++) {
            YWMaterialStock *beforeStock = self.ownMaterialArray[i];
            for (int j=0; j< self.selectedArray.count; j++) {
                YWMaterialStock *nowStock = self.selectedArray[j];
                if (beforeStock.stockId == nowStock.stockId) {
                    [self.ownMaterialArray removeObject:beforeStock];
                    i--;
                }
            }
        }
        [self.selectedArray addObjectsFromArray:self.ownMaterialArray];
        [self.delegate popSelectMaterials:self.selectedArray];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)willPresentSearchController:(UISearchController *)searchController{
    self.navigationController.navigationBar.translucent = YES;
}

- (void)willDismissSearchController:(UISearchController *)searchController{
    self.navigationController.navigationBar.translucent = NO;
}

-(NSString *)nameToPinYinWith:(NSString *)name
{
    HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
    [outputFormat setToneType:ToneTypeWithoutTone];
    [outputFormat setVCharType:VCharTypeWithV];
    [outputFormat setCaseType:CaseTypeLowercase];
    NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:name withHanyuPinyinOutputFormat:outputFormat withNSString:@""];
    return outputPinyin;
}

-(NSString *)namToPinYinFisrtNameWith:(NSString *)name
{
    NSString * outputString = @"";
    for (int i =0; i<[name length]; i++) {
        outputString = [NSString stringWithFormat:@"%@%c",outputString,pinyinFirstLetter([name characterAtIndex:i])];
        
    }
    return outputString;
}

- (void)dealloc{
    [_searchController.view removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
